package com.lagou.config;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XMLMapperBuilder {
    private Configuration configuration;
    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException, ClassNotFoundException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();

        preMappedStatement(rootElement, "select");
        preMappedStatement(rootElement, "insert");
        preMappedStatement(rootElement, "delete");
        preMappedStatement(rootElement, "update");

    }

    private void preMappedStatement(Element rootElement, String type) throws ClassNotFoundException {
        String namespace = rootElement.attributeValue("namespace");
        List<Element> select = rootElement.selectNodes(type);
        for (Element element : select) {
            String id = element.attributeValue("id");
            String paramterType = element.attributeValue("paramterType");
            String resultType = element.attributeValue("resultType");
            String sqlType = element.getQName().getName().toUpperCase();
            //入参 class
            Class<?> paraterTypeClass = getClassType(paramterType);
            //返回结果 class
            Class<?> resultTypeClass = getClassType(resultType);
            //statementId
            String key = namespace + "." + id;
            //sql 语句 原始的 未进行解析
            String sqlText = element.getTextTrim();
            //封装 mappedStatement
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setSql(sqlText);
            mappedStatement.setParamterType(paraterTypeClass);
            mappedStatement.setResultType(resultTypeClass);
            mappedStatement.setSqlType(sqlType);
            //填充 configuration
            configuration.getMappedStatementMap().put(key, mappedStatement);

        }
    }

    private Class<?> getClassType(String paramterType) throws ClassNotFoundException {
        if (paramterType==null || paramterType.equals("")){
            return null;
        }
        Class<?> cla = Class.forName(paramterType);
        return cla;
    }
}
